package com.chu.cloud.service.impl;

import com.chu.cloud.dto.MemberGetCouponDto;
import com.chu.cloud.entity.DiscountCoupon;
import com.chu.cloud.rabbit.RabbitConstants;
import com.chu.cloud.rabbit.direct.RabbitDirectSender;
import com.chu.cloud.repository.DiscountCouponRepository;
import com.chu.cloud.service.CouponService;
import com.chu.cloud.util.BeanUtil;
import com.chu.cloud.util.ChuException;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/5/3 17:08
 * @Description:
 */
@Service
@Slf4j
public class CouponServiceImpl implements CouponService {

    @Autowired
    private DiscountCouponRepository couponRepository;

    @Autowired
    private RabbitDirectSender rabbitSender;

    @Override
    public void cleanExpiredCoupon() {
        Date now = DateTime.now().toDate();
        List<DiscountCoupon> expiredCoupons = couponRepository.findByEndTimeLessThanEqual(now);
        expiredCoupons.forEach(c ->{
            c.setStatus(3);
        });
        couponRepository.save(expiredCoupons);
    }

    @Override
    public Integer userGetCoupon(Integer userId, Integer couponId) {
        DiscountCoupon discountCoupon = Optional.ofNullable(couponRepository.findOne(couponId))
                .orElseThrow(() -> new ChuException(String.format("优惠券%s不存在", couponId)));
        if (discountCoupon.getNumber() == 0){
            throw new ChuException("优惠券已经领取完了");
        }
        if (discountCoupon.getEndTime().compareTo(new Date()) < 0){
            log.error("已过领取时间,不可领取");
            return -1;
        }
        //发送消息到user服务
        MemberGetCouponDto coupon = new MemberGetCouponDto();
        BeanUtil.copyProperties(coupon,discountCoupon);
        coupon.setMemberId(userId);
        rabbitSender.sendDirectMessage(RabbitConstants.DirectQueueNameEnum.USER_GET_COUPON,
                coupon);
        return discountCoupon.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reduce(Integer couponId) {
        DiscountCoupon coupon = couponRepository.findOne(couponId);
        if (coupon.getNumber() == 0){
            return;
        }
        couponRepository.updateCoupon(couponId);
    }

}
